<template>
  <div id="app">
    <div class="todo-wrap">
      <my-header :receiveObject="receiveObject"></my-header>
      <my-list :todoList="todoList"
               :deleteItem="deleteItem"
               :changeItemStatus="changeItemStatus"></my-list>
      <my-footer :todoList="todoList"
                 :selectAllItem="selectAllItem"
                 :clearAllDoneItem="clearAllDoneItem"></my-footer>
    </div>
  </div>
</template>

<script>
import MyHeader from './components/MyHeader.vue'
import MyList from "./components/List.vue"
import MyFooter from './components/MyFooter.vue'

export default {
  name: 'App',
  components: {
    MyHeader,
    MyList,
    MyFooter
  },
  data () {
    return {
      // todoList: [
      //   { id: '001', hobby: '吃饭', done: false },
      //   { id: '002', hobby: '学习Vue', done: true },
      //   { id: '003', hobby: '泡妞', done: false },
      // ]
      todoList: JSON.parse(localStorage.getItem('todoList')) || []
    }
  },
  methods: {
    // 1.添加一个对象
    receiveObject (value) {
      // console.log("收到了从header传过来的数据", e);
      this.todoList.unshift(value)
    },
    // 2.改变item的选中状态
    changeItemStatus (id) {
      this.todoList.forEach((item) => {
        if (item.id == id) {
          item.done = !item.done
        }
      })
    },
    // 3.删除item
    deleteItem (id) {
      this.todoList = this.todoList.filter((item) => {
        return item.id != id
      })
    },
    // 4.底部全选或者反选
    selectAllItem (checked) {
      console.log(checked);
      // 4.1 直接使用for循环处理:low
      // for (let index = 0; index < this.todoList.length; index++) {
      //   this.todoList[index].done = checked
      // }
      //  console.log(this.todoList);
      // return this.todoList
      // 4.2 使用forEach方法
      this.todoList.forEach((item) => {
        item.done = checked
      })
    },
    // 5.清除已完成的任务
    clearAllDoneItem () {
      this.todoList = this.todoList.filter(item => item.done != true)
    }
  },
  watch: {
    todoList: {
      deep: true,
      handler (newValue, oldValue) {
        localStorage.setItem("todoList", JSON.stringify(newValue))
      }
    }
  }
}
</script>

<style>
body {
  background: #fff;
  width: 580px;
  margin: 0 auto;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
